﻿#light

namespace Twitter.Model

open System

type RequestBuilder(?username:string, ?password:string) =
    
    /// build an authentication header value by base64 encoding username:password
    let authHeader =
        match username,password with
        | Some username, Some password -> Some ("Basic " + Convert.ToBase64String((new Text.ASCIIEncoding()).GetBytes(username+":"+password)))
        | _, _ -> None  
    
    /// build a an http paramater string of type "param=arg&param2=arg2"
    let ParamStringBuilder(paramaters:list<string * string>) =
        paramaters |> Seq.map (fun (name, value) -> name+"="+value) |> String.concat "&"

    /// create a request to get the url with the paramaters supplied
    member this.BuildGetRequest(url:string, ?paramaters:list<string * string>) : Net.WebRequest =
        let paramString = 
            match paramaters with
            | None -> ""
            | Some [] -> ""
            | Some paramList -> "?" + ParamStringBuilder paramList
        
        let request = Net.WebRequest.Create(url + paramString)
        
        match authHeader with | Some header -> request.Headers.Add("Authorization", header)
                              | None -> ()
        request
        
    /// create a request to post the url with the paramaters supplied
    member this.BuildPostRequest(url:string, ?paramaters:list<string * string>) : Net.WebRequest =
        let request = Net.WebRequest.Create(url)
        request.Method <- "POST"
        request.ContentType <- "application/x-www-form-urlencoded"
        
        match authHeader with | Some header -> request.Headers.Add("Authorization", header)
                              | None -> ()
                              
        
        if paramaters.IsSome && paramaters <> Some [] then
            let data = Text.Encoding.UTF8.GetBytes(ParamStringBuilder paramaters.Value)
            request.ContentLength <- (int64)data.Length
            let stream = request.GetRequestStream()
            stream.Write(data, 0, data.Length)
            stream.Close()
        
        request 